﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class XBBoundary {
	public float xMin, xMax, zMin, zMax;
}

public class XBPlayerController : MonoBehaviour {

	public float speed;
	public float tilt;
	public XBBoundary boundary;

	public GameObject shot;
	public Transform shotSpawn;
	public float fireRate;
	private float nextFire;

	void Update() {
		if (Input.GetButton ("Fire1") && Time.time > nextFire) {
			nextFire = Time.time + fireRate;
			GameObject clone = Instantiate (shot, shotSpawn.position, shotSpawn.rotation) as GameObject;
			GetComponent<AudioSource> ().Play ();
		}
	}

	void FixedUpdate() {
		float moveHorizontal = Input.GetAxis ("Horizontal");
		float moveVertical = Input.GetAxis ("Vertical");

		Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
		GetComponent<Rigidbody> ().velocity = movement * speed;

		LimitPosition ();
		PlayTilt ();
	}  

	void LimitPosition() {
		Rigidbody body = GetComponent<Rigidbody> ();
		body.position = new Vector3 (
			Mathf.Clamp(body.position.x, boundary.xMin, boundary.xMax),
			0.0f,
			Mathf.Clamp(body.position.z, boundary.zMin, boundary.zMax)
		);
	}

	void PlayTilt() {
		Rigidbody body = GetComponent<Rigidbody> ();
		body.rotation = Quaternion.Euler (0.0f, 0.0f, body.velocity.x * -tilt);
	}
}
